function h = arrangeInGrid(digits,lbls,cols,rows,cellWidth,lblErrors,cLbls)
%if lblErrors is true an asterisk is used to mark mis-matches
%if cLbls is supplied it is assumed to be a cell array of strings and the
%labels are displayed over the corresponding column


[height width n] = size(digits);

assert(size(lbls,2)==n);


grid=ones(rows*cellWidth,cols*cellWidth);


padding=(1+(cellWidth-height)/2):(cellWidth-(cellWidth-width)/2);

if(lblErrors)
    %use first label as reference
    ref = num2str(lbls(1));
end

%Arrange digits in grid
for j=1:rows
    for i=1:cols
        padded = ones(cellWidth);
        
        padded(padding,padding)=digits(:,:,(j-1)*cols+i);
        
        %imshow(padded);
        
        grid((j-1)*cellWidth+1:j*cellWidth,(i-1)*cellWidth+1:i*cellWidth)=padded(:,:);
    end
end

h=figure;
imshow(grid);


%label digits
for j=1:rows
    for i=1:cols
        colOff=(i-1)*cellWidth+cellWidth/2;
        rowOff=(j-1)*cellWidth+cellWidth-(cellWidth-height)/4;
        
        if(nargin == 7 && j == 1)
            text(colOff,12,cLbls(i),'HorizontalAlignment','center','FontSize',12);
        end
        
        lab = num2str(lbls((j-1)*cols+i));
        
        if(lblErrors && lab ~= ref)
            lab=strcat(lab,'*');
        end
        
        text(colOff,rowOff,lab,'HorizontalAlignment','center','FontSize',12);
    end
end

end

